<script setup>
import {onMounted, ref, reactive} from "vue";
import axios from "axios";
import {CircleCloseFilled, Delete, Edit, Setting, SuccessFilled} from "@element-plus/icons-vue";

let cateList = ref([])
let queryInfo = ref({
  type: 3,
  pagenum: 1,
  pagesize: 5,
})
let total = ref(0)
let addCateDialogVisible = ref(false)
let editCateDialogVisible = ref(false)
let parentCateList = ref([])
let myCascaderProps = ref({
  value: 'cat_id',
  label: 'cat_name',
  children: 'children',
  checkStrictly: "true"
})
let selectedKeys = ref([])
let addCateFormRef = ref()
let editCateFormRef = ref()
let addCateForm = ref({
  // 分类名称
  cat_name: '',
  // 分类父级id
  cat_pid: 0,
  // 分类等级
  cat_level: 0,
})
let editCateForm = ref({
  // 分类名称
  cat_name: '',
  cat_id: 0
})
let addCateFormRules = ref({
  cat_name: [
    {required: true, message: '请输入分类名称', trigger: 'blur'},
    {min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur'}
  ]
})
let editCateFormRules = ref({
  cat_name: [
    {required: true, message: '请输入分类名称', trigger: 'blur'},
    {min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur'}
  ]
})
const getCateList = async () => {
  const {data: res} = await axios.get('categories', {params: queryInfo.value})
  if (res.meta.status !== 200) {
    ElMessage.error('获取商品分类失败')
    return
  }
  console.log(res)
  cateList.value = res.data.result
  total.value = res.data.total
}
const ParentCatList = async () => {
  const {data: res} = await axios.get('categories', {params: {type: 2}})
  if (res.meta.status !== 200) {
    ElMessage.error('获取商品父级分类失败')
    return
  }
  parentCateList.value = res.data
}
const parentCateChanged = () => {
  if (selectedKeys.value.length > 0) {
    // 获取父级分类Id
    addCateForm.value.cat_pid = selectedKeys.value[selectedKeys.value.length - 1]
    // 为当前分类等级赋值
    addCateForm.value.cat_level = selectedKeys.value.length
    return
  }
  addCateForm.value.cat_pid = 0
  addCateForm.value.cat_level = 0
}
const addCate = () => {
  // console.log(addCatForm.value)
  // const {data: res} = await axios.post('categories', addCatForm.value)
  addCateFormRef.value.validate(async isValid => {
    if (isValid) {
      const {data: res} = await axios.post('categories', addCateForm.value)
      if (res.meta.status !== 201) {
        ElMessage.error('添加商品分类失败')
        return
      }
      ElMessage.success('添加商品分类成功')
      getCateList()
      addCateDialogVisible.value = false
    }
  })
}
const editCate = () => {
  editCateFormRef.value.validate(async isValid => {
    if (isValid) {
      const {data: res} = await axios.put(`categories/${editCateForm.value.cat_id}`, {cat_name: editCateForm.value.cat_name})
      if (res.meta.status !== 200) {
        ElMessage.error('修改商品分类失败')
        return
      }
      getCateList()
      ElMessage.success('修改商品分类成功')
      editCateDialogVisible.value = false
    }
  })
}
const removeCateShowDialogById = async (cateId) => {
  editCateForm.value.cat_id = cateId
  const confirmResult = await ElMessageBox.confirm(
      '此操作将永久删除该商品分类, 是否继续?',
      '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
  ).catch(error => error)
  // console.log(confirmResult)
  if (confirmResult !== 'confirm') {
    ElMessage.info('取消删除')
    return
  }
  // console.log(editCateForm.value.cat_id)
  console.log(cateId)
  const {data: res} = await axios.delete(`categories/${editCateForm.value.cat_id}`)
  // console.log(res)
  if (res.meta.status !== 200) {
    ElMessage.error('删除商品分类失败')
  } else {
    ElMessage.success('删除商品分类成功')
    getCateList()
  }
}
const editCateShowDialog = (cateId) => {
  console.log(cateId)
  editCateForm.value.cat_id = cateId
  editCateDialogVisible.value = true
}
const addCateDialogClosed = () => {
  addCateFormRef.value.resetFields()
  addCateForm.value.cat_pid = 0
  addCateForm.value.cat_level = 0
  selectedKeys.value = []
}
const editCateDialogClosed = () => {
  editCateFormRef.value.resetFields()
  editCateForm.value.cat_name = ''
}
const handleSizeChange = (newSize) => {
  console.log(queryInfo.value.pagesize)
  queryInfo.value.pagesize = newSize
  getCateList()
}
const handleCurrentChange = (newPage) => {
  console.log(newPage)
  queryInfo.value.pagenum = newPage
  getCateList()
}
const indexMethod = () => (index) => index + 1

const showAddCateDialog = () => {
  ParentCatList()
  addCateDialogVisible.value = true
  editCateForm.value.cat_name = ''
}

onMounted(() => {
  getCateList()
})
</script>

<template>
  <div>
    <!-- 面包蟹导航区 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <!-- 分页区域 -->

    <el-card>
      <el-row>
        <el-col :span="24">
          <el-button type="primary" size="small" @click="showAddCateDialog()">添加分类</el-button>
        </el-col>
      </el-row>


      <!-- 表格 -->
      <el-table
          :data="cateList"
          style="width: 100%; margin-bottom: 20px"
          row-key="cat_id"
          border
          :default-expand-all="false"
      >
        <el-table-column type="index" :index="indexMethod()" sortable width="70px"/>
        <el-table-column prop="cat_name" label="分类名称" sortable/>
        <!-- 是否有效 -->
        <el-table-column label='是否有效' sortable>
          <template #default="scope">
            <div v-if="scope.row.cat_deleted === false">
              <el-icon style="color: lightgreen">
                <SuccessFilled/>
              </el-icon>
            </div>
            <div v-if="scope.row.cat_deleted === true">
              <el-icon style="color: red">
                <CircleCloseFilled/>
              </el-icon>
            </div>
          </template>
        </el-table-column>
        <!-- 排序 -->
        <el-table-column prop="cat_level" label="排序" width="150px">
          <template #default="scope">
            <div v-if="scope.row.cat_level ===0">
              <el-tag size="small">一级</el-tag>
            </div>
            <div v-if="scope.row.cat_level ===1">
              <el-tag type="success" size="small">二级</el-tag>
            </div>
            <div v-if="scope.row.cat_level ===2">
              <el-tag type="warning" size="small">三级</el-tag>
            </div>
          </template>
        </el-table-column>
        <!-- 操作 -->
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <!-- 编辑按钮 -->
            <el-button type="primary" :icon="Edit" size="small" @click="editCateShowDialog(scope.row.cat_id)"/>
            <!-- 删除按钮 -->
            <el-button type="danger" :icon="Delete" size="small" @click="removeCateShowDialogById(scope.row.cat_id)"/>
          </template>
        </el-table-column>
      </el-table>


      <!-- 分页 -->
      <div>
        <el-pagination
            :current-page="queryInfo.pagenum"
            :page-size="queryInfo.pagesize"
            :page-sizes="[3,5,10,15,20]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange">
        </el-pagination>
      </div>

    </el-card>

    <!-- 添加分类对话框  -->

    <el-dialog
        title="添加分类"
        width="50%"
        v-model="addCateDialogVisible"
        @close="addCateDialogClosed()"
    >

      <!-- 修改用分类单主体内容区域 -->
      <span>
        <el-form :model="addCateForm" :rules="addCateFormRules" ref="addCateFormRef" label-width="100px">
          <el-form-item label="分类名称" prop="cat_name">
             <el-input v-model="addCateForm.cat_name" type="text"></el-input>
          </el-form-item>
          <el-form-item label="父级分类" prop="cat_pid">
           <el-cascader expand-trigger="hover" :options="parentCateList"
                        v-model="selectedKeys"
                        :props="myCascaderProps"
                        @change="parentCateChanged()"
                        clearable
                        placeholder="请选择父级分类">
           </el-cascader>
          </el-form-item>

          <!--          <el-form-item label="电话" prop="mobile" type="text" placeholder="电话">-->
          <!--            <el-input v-model="addCatForm.mobile"></el-input>-->
          <!--          </el-form-item>-->
        </el-form>
      </span>
      <!-- 弹窗底部区域 -->
      <template #footer>
        <el-button @click="addCatDialogVisible = false">Cancel</el-button>
        <el-button type="primary" @click="addCate()">
          Confirm
        </el-button>
      </template>
    </el-dialog>

    <!-- 修改分类对话框 -->
    <el-dialog title="修改分类"
               width="50%"
               v-model="editCateDialogVisible"
               @close="editCateDialogClosed()"
    >
      <span>
        <el-form :model="editCateForm" :rules="editCateFormRules" ref="editCateFormRef" label-width="100px">
          <el-form-item label="分类名称" prop="cat_name">
            <el-input v-model="editCateForm.cat_name" type="text"></el-input>
          </el-form-item>
        </el-form>
      </span>
      <!-- 弹窗底部区域 -->
      <template #footer>
        <el-button @click="editCateDialogVisible = false">Cancel</el-button>
        <el-button type="primary" @click="editCate()">
          Confirm
        </el-button>
      </template>
    </el-dialog>

  </div>
</template>

<style scoped lang="less">
.el-Cascader {
  width: 100%;
}
</style>
